package com.itheima.reggie.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.*;
import com.itheima.reggie.domain.User;
import com.itheima.reggie.mapper.UserMapper;
import com.itheima.reggie.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

//用户
@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SmsTemplate smsTemplate;
    @Autowired
    private RedisTemplate redisTemplate;

    //发送短信
    @Override
    public void sendMsg(String phone) {
        // 1.生成6位随机数
        String code = RandomUtil.randomNumbers(6);
        code="123456"; // TODO 开发期间验证码写死
        // 2.发送sms短信
        // smsTemplate.sendSms(phone, code); // TODO 开发期间不发送短信
        // 3.将验证码存入redis
        redisTemplate.opsForValue().set("code:"+phone, code, Duration.ofSeconds(300));
    }

    //用户登录

    @Override
    public ResultInfo login(String phone, String code) {
        //1.校验验证码
        //1-1redis中的验证码
        String codeFromRedis = (String) redisTemplate.opsForValue().get("code:"+phone);
        //1-2比较，不一样登录失败
        //codeFromRedis.equals(code);//会出现空指针现象
        if (!StrUtil.equals(code, codeFromRedis)) {
            throw new CustomException("验证码不正确");
        }
        //2， 根据手机号查询数据库
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        qw.eq(User::getPhone, phone);
        User user = userMapper.selectOne(qw);
        //2-1新用户bangnizhuce
        if (user == null) {
            user = new User();
            user.setPhone(phone);
            user.setStatus(1);
            userMapper.insert(user);
        } else {
            //2-2老用户
            if (user.getStatus() != 1) {//状态不是1，此用户已被冻结
                throw new CustomException("\"您的账号已被冻结，请联系商家处理...\"");
            }
        }
        //3. 通过jwt制作token
       Map claims = new HashMap<>();
        claims.put("id", user.getId());
        claims.put("phone", user.getPhone());
        String token = JwtUtil.createToken(claims);
        //4. redis 存储完整的user对象（敏感 一天有效期）
        redisTemplate.opsForValue().set("phone" + user.getPhone(), user, Duration.ofDays(1));
        //5.清理验证码
        redisTemplate.delete("code:" + phone);
        System.out.println("==========");
        System.out.println(phone);
        //返回token
        return ResultInfo.success(token);
    }

    @Override
    public void logout() {
        redisTemplate.delete("phone" + UserHolder.get().getPhone());

    }
}
